package nciae.db.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import nciae.db.common.CommonResult;
import nciae.db.mapper.ExpertMapper;
//import nciae.db.mapper.SettingsMapper;
import nciae.db.mapper.SettingsMapper;
import nciae.db.mapper.StudentMapper;
import nciae.db.pojo.entity.Expert;
import nciae.db.pojo.entity.Settings;
import nciae.db.pojo.entity.Student;
import nciae.db.pojo.entity.User;
import nciae.db.pojo.vo.QueryExportVO;
import nciae.db.service.ExpertService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ExpertServiceImpl extends ServiceImpl<ExpertMapper, Expert> implements ExpertService {
    @Autowired
    private ExpertMapper expertMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private SettingsMapper settingsMapper;
    @Override
    public CommonResult<List<String>> listExpertName(){
        CommonResult<List<String>>  rs = new CommonResult<>();
        try{
            QueryWrapper<Expert> expertQueryWrapper = new QueryWrapper<>();
            expertQueryWrapper.select("name").groupBy("name");
            List<String> expertNameList = expertMapper.selectMaps(expertQueryWrapper).stream().map(map -> map.get("name").toString()).collect(Collectors.toList());
            rs.setCode(0);
            rs.setMsg("查询成功");
            rs.setData(expertNameList);
            return rs;
        }catch (Exception e){
            rs.setCode(-1);
            rs.setMsg("发生错误"+e.getMessage());
            return rs;
        }
    }

    @Override
    public CommonResult<List<Expert>> search(Integer page, Integer limit, String name, String department, String title){
        CommonResult<List<Expert>>  rs = new CommonResult<>();
        try{
            QueryWrapper<Expert> expertQueryWrapper = new QueryWrapper<>();
            if(name!=null&&!name.isEmpty()){
                expertQueryWrapper.eq("name",name);
            }
            if(department!=null&&!department.isEmpty()){
                expertQueryWrapper.eq("department",department);
            }
            if(title!=null&&!title.isEmpty()){
                expertQueryWrapper.eq("title",title);
            }
            List<Expert> experts = expertMapper.selectList(expertQueryWrapper);
            rs.setCode(0);
            rs.setMsg("查询成功");
            rs.setData(experts);
            return rs;
        }
        catch (Exception e){
            rs.setCode(-1);
            rs.setMsg("发生错误"+e.getMessage());
            return rs;
        }
    }
    @Override
    public CommonResult<List<QueryExportVO>> getAllExperts() {
        // 这里是获取专家的逻辑，可以从数据库获取
        CommonResult<List<QueryExportVO>>  rs = new CommonResult<>();
        List<Student>students= studentMapper.selectList(null);
        Map<Integer,Integer> countStudentsPerExpert = countStudentsPerExpert(students);
        for (Map.Entry<Integer, Integer> entry : countStudentsPerExpert.entrySet()) {
            Integer expertId = entry.getKey();
            Integer studentCount = entry.getValue();

            // 更新专家表中的学生数量
            Expert expert = expertMapper.selectById(expertId); // 假设你有一个专家Repository来查找专家

            if (expert != null) {
                expert.setPlaces(studentCount);  // 设置新的学生数量
                expertMapper.updateById(expert);           // 更新数据库中的专家记录
            }
        }
        try{
            List<Expert> experts = expertMapper.selectList(null);
            List<QueryExportVO> exports = new ArrayList<>();
            Settings settings = settingsMapper.getSettings();
            Integer stuMaxNum=settings.getStuMaxNum();
            for (Expert expert : experts) {
                QueryExportVO export = QueryExportVO.builder()
                        .id(expert.getId())
                        .name(expert.getName())
                        .department(expert.getDepartment())
                        .title(expert.getTitle())
                        .tel(expert.getTel())
                        .email(expert.getEmail())
                        .introduce(expert.getIntroduce())
                        .userName(expert.getUserName())
                        .userPwd(expert.getUserPwd())
                        .places(expert.getPlaces())
                        .build();

                export.setStuMaxNum(stuMaxNum);

                exports.add(export);
            }
            //根据places排序
            exports.sort((o1, o2) -> o1.getPlaces() - o2.getPlaces());
            rs.setCode(0);
            rs.setMsg("查询成功");
            rs.setData(exports);
            return rs;
        }catch (Exception e){
            rs.setCode(-1);
            rs.setMsg("发生错误"+e.getMessage());
            return rs;
        }
    }
    @Override
    public Map<Integer, Integer> countStudentsPerExpert(List<Student> students) {
        if (students == null || students.isEmpty()) {
            return Collections.emptyMap();
        }
        try {
            return students.stream()
                    .filter(student -> student.getExpertId() != null) // 过滤掉 expertId 为 null 的学生
                    .collect(Collectors.groupingBy(Student::getExpertId, Collectors.summingInt(s -> 1)));
        } catch (Exception e) {
            throw new RuntimeException("统计学生数量时发生错误: " + e.getMessage(), e);
        }
    }

    @Override
    public CommonResult<Expert> expertSave(Expert expert){
        CommonResult<Expert>  rs = new CommonResult<>();
        try{
            if (expert.getId()==0 || expert.getId()==null){
                expert.setUserPwd("123456");  // 默认密码
                expertMapper.insert(expert);
                rs.setCode(0);
                rs.setMsg("添加成功");
                rs.setData(expert);
                return rs;
            }else {
                expertMapper.updateById(expert);
                rs.setCode(0);
                rs.setMsg("保存成功");
                rs.setData(expert);
                return rs;
            }
        }catch (Exception e){
            rs.setCode(-1);
            rs.setMsg("发生错误"+e.getMessage());
            return rs;
        }
    }

    @Override
    public Expert getExpertInfo(Integer expertId){
        Expert expert = expertMapper.selectById(expertId);
        return expert;
    }


    @Override
    public CommonResult delete(Integer id){
        CommonResult rs = new CommonResult();
        try{
            int k = expertMapper.deleteById(id);
            if (k>0){
                rs.setCode(0);
                rs.setMsg("删除成功");
            }else {
                rs.setCode(-1);
                rs.setMsg("删除失败");
            }
            return rs;
        }
        catch (Exception e){
            rs.setCode(-1);
            rs.setMsg("发生错误"+e.getMessage());
            return rs;
        }
    }

    @Override
    public void setUserInfo(User user){
        Expert expert = expertMapper.selectOne(new QueryWrapper<Expert>().eq("user_name",user.getUserName()));
        if (expert!=null){
            expert.setUserName(user.getUserName());
            expert.setUserPwd(user.getUserPwd());
            expert.setName(user.getRealName());
            expert.setTel(user.getTel());
            expert.setEmail(user.getEmail());
            expert.setDepartment(user.getDepartment());
            expert.setTitle(user.getTitle());
            expert.setIntroduce(user.getIntroduce());
            expertMapper.updateById(expert);
        } else {
            expert = new Expert();
            expert.setUserName(user.getUserName());
            expert.setUserPwd(user.getUserPwd());
            expert.setName(user.getRealName());
            expert.setTel(user.getTel());
            expert.setEmail(user.getEmail());
            expert.setDepartment(user.getDepartment());
            expert.setTitle(user.getTitle());
            expert.setIntroduce(user.getIntroduce());
            expert.setPlaces(0);
            expertMapper.insert(expert);
        }
    }
}
